const express = require("express");
const userRouter = require("./router/user.js");
const userInfoRouter = require("./router/userinfo.js");
const cors = require("cors");
const joi = require("joi");
const expressJWT = require("express-jwt");
const config = require("./config");

const app = express();

app.use(cors());

app.use(function (req, res, next) {
  res.errorHandler = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});

app.use(
  expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] })
);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use("/api", userRouter);

// 注意：以 /my 开头的接口，都是有权限的接口，需要进行 Token 身份认证
app.use("/my", userInfoRouter);

app.use(function (err, req, res, next) {
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.errorHandler(err);
  if (err.name === "UnauthorizedError") {
    return res.errorHandler("token 身份认证失败");
  }

  // next();
});

app.listen(3007, () => {
  console.log("api server running at http://127.0.0.1:3007");
});
